package com.getjsp.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpDownload {
private URL url = null;

	
	public String download(String urlStr)  {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			
			url = new URL(urlStr);
			
			HttpURLConnection urlConn = (HttpURLConnection) url
					.openConnection();
				urlConn.setReadTimeout(15000);
				urlConn.setRequestMethod("POST");
						buffer = new BufferedReader(new InputStreamReader(urlConn
					.getInputStream()));
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		} finally {
			try {
				buffer.close();
			} catch (Exception e) {
				e.printStackTrace();
				return "error";
			}
		}
		return sb.toString();
	}

	
	public int downFile(String urlStr, String path, String fileName) {
		InputStream inputStream = null;
		try {
			FileUtils fileUtils = new FileUtils();
			
			if (fileUtils.isFileExist(path + fileName)) {
				return 1;
			} else {
				inputStream = requestHttp(urlStr);
				File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream);
				if (resultFile == null) {
					return -1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	
	
	public static InputStream requestHttp(String urlStr){
		InputStream inStream = null;
		try {
			URL url = new URL(urlStr);					
			HttpURLConnection con = (HttpURLConnection)url.openConnection();
			con.setRequestMethod("GET");
			con.setConnectTimeout(15000);
			
			int respCode = con.getResponseCode();	
			
            if (respCode == 200)
            {
            	inStream = con.getInputStream();
                return inStream;
            }

			
			} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;	
		
	}
}
